package br.com.foxline.atlasmobile;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import br.com.foxline.atlasmobile.dao.BairroDao;
import br.com.foxline.atlasmobile.dao.CityDao;
import br.com.foxline.atlasmobile.dao.DneDao;
import br.com.foxline.atlasmobile.dao.EnderecoDao;
import br.com.foxline.atlasmobile.dao.ImovelDao;
import br.com.foxline.atlasmobile.entities.Dne;
import br.com.foxline.atlasmobile.entities.Endereco;
import br.com.foxline.atlasmobile.entities.Imovel;
import br.com.foxline.atlasmobile.entities.Proprietario;
import br.com.foxline.atlasmobile.enums.SituacaoImovel;

public class LocalizacaoActivity extends Activity {

	private List<String> bairros;
	
	private static String IMOVEL = "getimovel";

	// DAO
	private ImovelDao imovelDao;
	private DneDao dneDao;

	private EnderecoDao enderecoDao;

	private Imovel imovel;

	private EditText cep;
	private EditText logradouro;
	private EditText numero;
	private EditText comple;
	private Spinner bairro;

	private Endereco endereco;

	private BairroDao bairroDao;

	
	private void searchDne(String cep){
		Dne dne = dneDao.getDne(cep);
		
		if(dne != null){
			dne.setBairro(bairroDao.find(dne.getBairro().getId()));
			this.logradouro.setText(dne.getNomeclog());
			this.bairro.setSelection(bairros.indexOf(dne.getBairro().getNome()));
			
			this.logradouro.setEnabled(false);
			this.bairro.setEnabled(false);
			this.numero.requestFocus();
		}else{
			Toast.makeText(getApplicationContext(), "Endereço não encontrado !", Toast.LENGTH_SHORT).show();
			this.logradouro.setEnabled(true);
			this.bairro.setEnabled(true);
		}
	}
	
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_localizacao);

	
		dneDao = new DneDao(getApplicationContext());
		bairroDao = new BairroDao(getApplicationContext());
		
		cep = (EditText) findViewById(R.id.cep);
		cep.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence value, int arg1, int arg2, int arg3) {
				
				if(value != null && value.length() == 8){
					searchDne(String.valueOf(value));
				}else{
					logradouro.setEnabled(true);
					bairro.setEnabled(true);
				}
			}
			
			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				
			}
			
			@Override
			public void afterTextChanged(Editable arg0) {
				
				
			}
		});
		
		logradouro = (EditText) findViewById(R.id.logradouro);
		numero = (EditText) findViewById(R.id.num);
		comple = (EditText) findViewById(R.id.compl);
		bairro = (Spinner) findViewById(R.id.nome_bairro);
		
		
		bairros = bairroDao.getBairros(new CityDao(getApplicationContext()).getCity("Parnaíba"));
		
		bairro.setAdapter(new ArrayAdapter<String>(
				getApplicationContext(),
				R.layout.spinner_item,
				bairros));

		if (getIntent().getSerializableExtra(IMOVEL) != null) {

			imovelDao = new ImovelDao(getApplicationContext());
			enderecoDao = new EnderecoDao(getApplicationContext());

			imovel = (Imovel) getIntent().getSerializableExtra(IMOVEL);

			if (imovel.getEnderecoImovel() != null){
				endereco = imovel.getEnderecoImovel();
				cep.setText(endereco.getCep());
				logradouro.setText(endereco.getLogradouro());
				numero.setText(valueOf(endereco.getNumero()));
				comple.setText(endereco.getCompl());
				bairro.setSelection(bairros.indexOf(endereco.getBairro()));
				
			}else{
				endereco = new Endereco();
			}

		} else {
			imovel = new Imovel();
			endereco = new Endereco();
		}
	}
	
	public String valueOf(Integer x){
		if(x != null){
			return String.valueOf(x);
		}
		return "";
	}

	public void save() {
		enderecoDao = new EnderecoDao(getApplicationContext());
		imovelDao = new ImovelDao(getApplicationContext());

		endereco.setCep(cep.getText().toString());
		endereco.setLogradouro(logradouro.getText().toString());
		endereco.setNumero(parseInt(numero.getText().toString()));
		endereco.setCompl(comple.getText().toString());
		endereco.setBairro((String) bairro.getSelectedItem());

		if (endereco.getId() == null) {
			enderecoDao.create(endereco);
		} else {
			enderecoDao.update(endereco);
		}

		imovel.setEnderecoImovel(endereco);
		imovelDao.update(imovel);
		

	}

	public Integer parseInt(String str) {
		try {
			return (Integer.parseInt(str));
		} catch (Exception e) {
			return null;
		}

	}

	public void next(View view) {
		save();
		Intent intent = new Intent(getApplicationContext(),
				ProprietarioActivity.class);
		intent.putExtra(IMOVEL, imovel);
		startActivity(intent);
		overridePendingTransition(R.anim.slide_in_right,
				R.anim.slide_out_left);
		finish();
	}

	public void previous(View view) {
		save();
		Intent intent = new Intent(getApplicationContext(),
				CreateMainActivity.class);
		intent.putExtra(IMOVEL, imovel);
		startActivity(intent);
		finish();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_localizacao, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.finalizar:
			dialogSituacao();
			break;
		case R.id.sair:
			Intent intent = new Intent(this, MenuActivity.class);
			startActivity(intent);
			try {
				finalize();
			} catch (Throwable e) {
				e.printStackTrace();
			}
		break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	public void dialogSituacao() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Situação do Imóvel");

		final String[] items = new String[SituacaoImovel.values().length];
		int cont = 0;
		final Map<Integer, SituacaoImovel> map = new HashMap<Integer, SituacaoImovel>();

		for (SituacaoImovel si : SituacaoImovel.values()) {
			items[cont] = si.toString();
			map.put(cont, si);
			cont++;
		}

		builder.setItems(items, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				imovel.setSituacaoImovel(map.get(which));
				save();
				imovel.getSituacaoImovel();
				finalCadastro();
			}
		});

		AlertDialog dsituacao = builder.create();
		dsituacao.show();
	}

	public void finalCadastro() {

		AlertDialog dialog;

		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		builder.setNeutralButton("Finalizar e usar como modelo",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {

						Intent intent = new Intent(getApplicationContext(),
								CreateMainActivity.class);

						imovel.setId(null);

						if (imovel.getEnderecoImovel() != null)
							imovel.getEnderecoImovel().setId(null);
						if (imovel.getEnderecoCorrespondencia() != null)
							imovel.getEnderecoCorrespondencia().setId(null);
						if (imovel.getAnnex() != null) {
							imovel.setAnnex(null);
						}
						if (imovel.getDimensoes() != null) {
							imovel.getDimensoes().setId(null);
						}
						if (imovel.getProprietarios() != null) {
							for (Proprietario p : imovel.getProprietarios()) {
								p.setId(null);
							}
						}

						intent.putExtra(IMOVEL, imovel);

						startActivity(intent);
						finish();

					}
				});

		builder.setPositiveButton("Finalizar",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {

						Intent intent = new Intent(getApplicationContext(),
								MenuActivity.class);
						startActivity(intent);
						finish();

					}
				});

		builder.setNegativeButton("Não", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {

			}
		});

		builder.setMessage("Desejar finalizar o cadastro").setTitle(
				"Cadastro Finalizado");

		dialog = builder.create();
		dialog.show();
	}
}
